<?php
Yii::import('SolrUtil');
class GoodsController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions() {
		return array(

		);
	}
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules()
    {
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions
                'actions'=>array('getGoodsByNew','getGoodsByHot','getGoodsDetail','getGoodsTechnology','share','prise','getGoodsComments','getSales','findGoodsByCategory','gettag','search',
                    'findGoodsByKey'),
                'users'=>array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('favorites','addGoodsComment'),
                'users'=>array('@'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }

    public function actionGetTag()
    {
        $result = Tag::model()->findAll();
        $arr = array();
        $local = CommonUtils::getLocal();

        if ($local==_LOCAL_ZN) {
            $name_field ='name_zn';
        } else {
            $name_field ='name_en';
        }
        foreach ($result as $key => $value) {
            array_push($arr, $value[$name_field]);
        }
        echoToMobile($arr);
    }

    /**
     * 最新商品
     * @param int $sort
     * @param $shelfTime
     */
    public function actionGetGoodsByNew($sort=EMongoCriteria::SORT_DESC,$start=0) {
        $resultArr = array();
        $local = CommonUtils::getLocal();

        if ($local==_LOCAL_ZN) {
            $desc_field ='desc_zn';
            $name_field = 'name_zn';
        } else {
            $desc_field ='desc_en';
            $name_field = 'name_en';
        }

        if ($sort==EMongoCriteria::SORT_DESC) {
            $sortflag = '<';
        } else {
            $sortflag = '>';
        }
        //类别查询条件
        $query = array(
            'conditions'=>array('selling' =>array('==' => true, ) , ),
            'limit'=>_LIMITED_PAGE_SIZE,
            'sort'=> array('updatetime'=>(int)$sort),
            'select'=>array($name_field,'selling','_id','originPrice','icon','updatetime'),
            'offset'=>$start,
        );
        // if ($updatetime==-1) {
        //     $query['conditions'] = array('status'=>array('!='=>_GOODS_STATUS_DEL),'selling'=>array('=='=>true));
        // } else {
        //     $query['conditions'] = array('status'=>array('!='=>_GOODS_STATUS_DEL),'selling'=>array('=='=>true),'updatetime'=>array($sortflag=>(int)$updatetime));
        // }
        $goods = Goods::model()->findAll($query);
        if (!empty($goods) && count($goods)>0) {
            $len = count($goods);
            for($index=0;$index<$len;$index++) {
                $item = array();
                // $item['desc'] = $goods[$index][$desc_field];
                // $item['selling'] = $goods[$index]['selling'];
                $item['name'] = $goods[$index][$name_field];
                $item['id'] = (string)$goods[$index]['_id'];
                $item['icon'] = (string)$goods[$index]['icon'];
                $price = RedisCacheUtil::getPrice($item['id']);
                if (!empty($price) && $item['selling']==true) {
                    $item['price'] = (int)$price;
                } else {
                    $item['price'] = (int)$goods[$index]['originPrice'];
                }
                $item['hotnum'] = (int)RedisCacheUtil::getGoodsHot($item['id']);
                $item['updatetime'] = $goods[$index]['updatetime'];
                array_push($resultArr,$item);
            }
        }
        echoToMobile($resultArr);
    }

    /**
     * 最热商品
     * @param int $sort
     * @param int $start
     */
    public function actionGetGoodsByHot($sort=EMongoCriteria::SORT_DESC,$start=0) {
        $resultArr = array();
        if ($sort==EMongoCriteria::SORT_DESC) {
            $gids = Yii::app()->redis->ZREVRANGE(_REDIS_SORTLIST_GOODSHOTS,$start,$start+_LIMITED_PAGE_SIZE,'WITHSCORES');
        } else {
            $gids = Yii::app()->redis->ZRANGE(_REDIS_SORTLIST_GOODSHOTS,$start,$start+_LIMITED_PAGE_SIZE,'WITHSCORES');
        }
        if (!empty($gids)&& count($gids)>0) {
            $keyArr=array_keys($gids);

            $local = CommonUtils::getLocal();


            if ($local==_LOCAL_ZN) {
                $desc_field ='desc_zn';
                $name_field = 'name_zn';
            } else {
                $desc_field ='desc_en';
                $name_field = 'name_en';
            }
            $mids = array();
            for($index=0;$index<count($keyArr);$index++) {
                try {
                    array_push($mids,new MongoId($keyArr[$index]));
                } catch(Exception $ex){
                    //TODO 临时用来解决测试数据非法的问题
                }
            }
            //类别查询条件
            $query = array(
                'conditions'=>array('status'=>array('!='=>-1),'_id'=>array('in'=>$mids)),
                'select'=>array($name_field,'selling','_id','originPrice','icon'),
            );
            $goods = Goods::model()->findAll($query);
            if (!empty($goods) && count($goods)>0) {
                $len = count($goods);
                for($index=0;$index<$len;$index++) {
                    $item = array();
                    // $item['desc'] = $goods[$index][$desc_field];
                    // $item['selling'] = $goods[$index]['selling'];
                    $item['name'] = $goods[$index][$name_field];
                    $item['id'] = (string)$goods[$index]['_id'];
                    $item['icon'] = (string)$goods[$index]['icon'];
                    $item['hotnum'] = $gids[$item['id']];
                    $price = RedisCacheUtil::getPrice($item['id']);
                    if (!empty($price) && $item['selling']==true) {
                        $item['price'] = (int)$price;
                    } else {
                        $item['price'] = (int)$goods[$index]['originPrice'];
                    }
                    array_push($resultArr,$item);
                }
            }
        }
        echoToMobile($resultArr);
    }

    /**
     * 得到商品详情
     *
     * @param $id
     */
    public function actionGetGoodsDetail($id) {
        $goodsResult = array();
        $local = CommonUtils::getLocal();

        if ($local==_LOCAL_ZN) {
            $desc_field ='desc_zn';
            $name_field = 'name_zn';
            $material_field='material_zn';
            $placeOfOrigin_field='placeOfOrigin_zn';
        } else {
            $desc_field ='desc_en';
            $name_field = 'name_en';
            $material_field='material_en';
            $placeOfOrigin_field='placeOfOrigin_en';
        }

        $mongoid = new MongoId($id);
        $query = array(
            'conditions' => array('_id'=>array('=='=>$mongoid)),
            'select'=>array($name_field,$desc_field,$material_field,$placeOfOrigin_field,'code','shopimage','shopaddress','originPrice','selling','size','shelfTime','images','icon','_id','brand'),
        );
        $result = Goods::model()->find($query);
        if (!empty($result)) {
            if ($result->status==_GOODS_STATUS_DEL) {
                echoToError(_ERROR_GOODS_HAS_UNSELF);
            }
            //**********商品基本信息***********//
            $goodsResult['id'] = (string)$result->toArray()['_id'];
            //商品名称
            $goodsResult['name'] = $result->toArray()[$name_field];
            //商品品牌专卖店图片
            $goodsResult['shopimage'] = $result->toArray()['shopimage'];
            //商品品牌专卖店地址
            $goodsResult['shopaddress'] = $result->toArray()['shopaddress'];
            //商品原价
            $goodsResult['originPrice'] =$result->toArray()['originPrice'];
            //商品图片
            $goodsResult['images'] = $result->toArray()['images'];
            //商品预览图
            $goodsResult['icon'] = $result->toArray()['icon'];
            $goodsResult['code'] = $result->toArray()['code'];

            //**********商品简介***********//
            $goodsResult['desc'] = $result->toArray()[$desc_field];
            //尺寸
            $goodsResult['size'] = $result->toArray()['size'];
            //材质
            $goodsResult['material'] = $result->toArray()[$material_field];
            //原产地
            $goodsResult['placeOfOrigin'] = $result->toArray()[$placeOfOrigin_field];

            //**********商品销售***********//
            $goodsResult['selling'] = $result->toArray()['selling'];
            $goodsResult['shelfTime'] = $result->toArray()['shelfTime'];

            $auction = $this->getGoodsAuction($goodsResult['id'],_GOODS_AUCTION_STATE_PROCESS);
            if (!empty($auction)) {
                $goodsResult['starttime'] =$auction->starttime;
                $goodsResult['endtime'] =$auction->endtime;
                $goodsResult['code'] =$auction->flowcode;
                $goodsResult['auctionid'] = (string)$auction->_id;
            } else {
                $goodsResult['starttime'] =0;
                $goodsResult['endtime'] =0;
                $goodsResult['auctionid'] = "0";
            }
            //其他统计信息
            $goodskey = $goodsResult['id'];
            $this->browserRecord($goodsResult['id']);
            $goodsResult['hotNum'] = RedisCacheUtil::getGoodsHot($goodskey);
            $goodsResult['hasFavorites'] = $this->hasFavorites($goodskey);
        }

        $goodsResult['brandname'] = Brand::model()->findByPk(new MongoId($result->brand))->name_zn;
        echoToMobile($goodsResult);
    }


    /**
     * 得到商品技术规格
     *
     * @param $id
     */
    public function actionGetGoodsTechnology($id) {
        $local = CommonUtils::getLocal();

        if ($local==_LOCAL_ZN) {
            $technology_field='technology_zn';
        } else {
            $technology_field='technology_en';
        }
        $mongoid = new MongoId($id);
        $query = array(
            'conditions' => array('_id'=>array('=='=>$mongoid)),
            'select'=>array($technology_field,'_id',),
        );
        $result = Goods::model()->find($query);
        $ra = array();
        if (!empty($result)) {
            $ra['technology'] = $result->toArray()[$technology_field];
        } else {
            $ra['technology'] = "";
        }
        echoToMobile($ra);
    }


    /**
     * 添加关注
     * @param $id 商品id
     */
    public function actionFavorites($id) {
        $query = array(
            'conditions' => array('goods'=>array('=='=>$id),'userid'=>array('=='=> CommonUtils::getUserId())),
        );
        $ua = UserAttention::model()->find($query);
        if (!empty($ua)) {
            echoToError(_ERROR_ALREADY_FAVORITES);
        } else {
            $useraction = new UserActionlog();

            $useraction->userid = CommonUtils::getUserId();

            $useraction->event = _USER_ACTION_FAVORITES;
            $useraction->entityObject = $id;
            $useraction->createTime = time();
            $useraction->entityType = _CHANNEL_GOODS;
            $useraction->save(false);

            $userAttention =new UserAttention();
            $userAttention->userid = CommonUtils::getUserId();
            $userAttention->goods = $id;
            $userAttention->save(false);
            $this->addToTotal($id,_USER_ACTION_FAVORITES);
            echoToMobile("ok");
        }
    }

    /**
     * 分享
     * @param $id 商品id
     */
    public function actionShare($id) {
        $useraction = new UserActionlog();
        $useraction->userid = CommonUtils::getUserId();
        $useraction->event = _USER_ACTION_SHARE;
        $useraction->entityObject = $id;
        $useraction->createTime = time();
        $useraction->save();
        $this->addToTotal($id,_USER_ACTION_SHARE);
        echoToMobile("ok");
    }

    /**
     * 赞
     * @param $id 商品ids
     * @param $deviceid 设备IDS
     */
    public function actionPrise($id,$deviceid) {
        $query = array(
            'conditions' => array('entityObject'=>array('=='=>$id),'deviceid'=>array('=='=>$deviceid),'event'=>array('=='=>_USER_ACTION_PRISE)),
        );
        $reuslt = UserActionlog::model()->find($query);
        if (!empty($reuslt)) {
            echoToError(_ERROR_ALREADY_PRISE);
        } else {
            $useraction = new UserActionlog();
            $useraction->userid = CommonUtils::getUserId();
            $useraction->event = (int)_USER_ACTION_PRISE;
            $useraction->entityObject = $id;
            $useraction->deviceid = $deviceid;
            $useraction->createTime = time();
            $useraction->entityType = _CHANNEL_GOODS;
            $useraction->save();
            $this->addToTotal($id,_USER_ACTION_PRISE);
            echoToMobile("ok");
        }
    }

    /**
     * 添加商品评论
     */
    public function actionAddGoodsComment() {
        $local = CommonUtils::getLocal();
        $query = array(
            'conditions'=>array('goods'=>array('=='=>$_POST['gid']),
                'status'=>array('!='=>_ORDER_STATE_WAIT_PAID),
                'status'=>array('!='=>_ORDER_STATE_CANCEL),
                'userid'=>array('=='=>CommonUtils::getUserId()),
                ),
        );
        $order = Order::model()->find($query);
        if (!empty($order)) {
            $comment = new GoodsComment();
            $comment->goods = $_POST['gid'];
            $comment->createtime = time();
            $comment->grade = $_POST['grade'];
            $comment->content =$_POST['content'];
            $comment->local = $local;
            $comment->userid = CommonUtils::getUserId();
            $comment->save(false);
        } else {
            echoToError(__ERROR_GOODS_UNCOMMENT);
        }

        echoToMobile("ok");
    }

    /**
     * 获得商品评论
     * @param $id 商品id
     * @param int $time 评论时间
     */
    public function actionGetGoodsComments($id,$createtime=0) {
        $resultArr = array();
        $local = CommonUtils::getLocal();

        $query['select'] =  array('content','userid','createtime','grade');
        $query['limit'] = _LIMITED_PAGE_SIZE;
        $query['sort'] = array('createtime'=>EMongoCriteria::SORT_DESC);
        if ($createtime>0) {
            $query['conditions'] = array('goods'=>array('=='=>$id),'createtime'=>array('<'=>$createtime),'local'=>array('=='=>$local));
        } else {
            $query['conditions'] = array('goods'=>array('=='=>$id),'local'=>array('=='=>$local));
        }
        $result = GoodsComment::model()->findAll($query);
        if (!empty($result) && count($result)>0) {
            $len = count($result);
            for($index=0;$index<$len;$index++) {
                $item = array();
                $item['content'] = $result[$index]['content'];
                $item['grade'] = $result[$index]['grade'];
                $item['createtime'] = $result[$index]['createtime'];
                $userinfo=$this->getUser($result[$index]['userid']);
                $item['nickname'] = $userinfo->nickname;
                $item['icon'] = $userinfo->icon;
                array_push($resultArr,$item);
            }
        }
        echoToMobile($resultArr);
    }


    /**
     * 获得sales信息
     * @param $id 商品ID
     */
    public function actionGetSales($id,$limited=_LIMITED_SALES_NUMBERS) {
        $resultArr = array();
        $auctionInfo = $this->getGoodsAuction($id);
        if (!empty($auctionInfo)) {
            $auctionid = (string)$auctionInfo->_id;
            $query = array(
                'conditions' => array('auction'=>array('=='=>$auctionid)),
                'limit'=>$limited,
                'sort'=> array('price'=>EMongoCriteria::SORT_ASC)
            );
            $salesoffers = SalesOffer::model()->findAll($query);

            if (!empty($salesoffers)) {
                $len = count($salesoffers);
                for($index=0;$index<$len;$index++) {
                    $item = array();
                    $item['price'] = $salesoffers[$index]['price'];
                    $item['sales'] = $this->getSales($salesoffers[$index]['sales'])->nickname;
                    $item['offerTime'] = $salesoffers[$index]['offerTime'];
                    array_push($resultArr,$item);
                }
            }
        }
        echoToMobile($resultArr);
    }


    public function actionFindGoodsByCategory($code,$start=0,$sort='price',$type=_SORT_ASC)
    {
        $local = CommonUtils::getLocal();

        if ($local==_LOCAL_ZN) {
            $local = _SOLR_GOODS_ZN;
        } else {
            $local = _SOLR_GOODS_EN;
        }

        $solrUtil = new SolrUtil(_SOLR_ADDRESS, $local);
        $fields = 'id originPrice price name icon';
        $result = $solrUtil->select(array('q'=>'categorycode:'.$code.'*','pageSize'=>10,'fl'=>$fields,'page'=>$start,'sort'=>$sort." ".$type));

        $body = array();
        // $body['nums'] = $result['data']['response']['numFound'];
        $body = $result['data']['response']['docs'];

        echoToMobile($this->composeSearchResult($body));
    }

    public function actionFindGoodsByKey($key,$start=0,$sort='price',$type=_SORT_ASC)
    {
        $local = CommonUtils::getLocal();

        if ($local==_LOCAL_ZN) {
            $local = _SOLR_GOODS_ZN;
        } else {
            $local = _SOLR_GOODS_EN;
        }

        $solrUtil = new SolrUtil(_SOLR_ADDRESS, $local);
        $fields = 'id originPrice price name icon';
        $queryKey = "(name:{$key} + technology:{$key} + brandname:{$key}) AND (channel:GOODS)";
        $result = $solrUtil->select(array('q'=>$queryKey,'pageSize'=>10,'page'=>$start,'fl'=>$fields,'sort'=>$sort." ".$type));

        $body = array();
        // $body['nums'] = $result['data']['response']['numFound'];
        $body = $result['data']['response']['docs'];

        echoToMobile($this->composeSearchResult($body));
    }


    public function actionSearch($category ="",$brand = "",$tag ="",$start=0,$sort='price',$type=_SORT_ASC)
    {
        // $category = ;
        // $brand = $_POST['brand'];
        // $tag = $_POST['tag'];
        $category = explode(',.', $category);
        $brand = explode(',.', $brand);
        $tag = explode(',.', $tag);
        foreach ($category as $key => $value) {
            if(empty($value))
                continue;
            if(empty($categoryCon))
                $categoryCon = 'categoryname:"'.$value.'"';
            else
                $categoryCon = $categoryCon.' OR categoryname:"'.$value.'"';
        }
        $brandCon = "";
        foreach ($brand as $key => $value) {
            if(empty($value))
                continue;
            if(empty($brandCon))
                $brandCon = 'brandname:"'.$value.'"';
            else
                $brandCon = $brandCon.' OR brandname:"'.$value.'"';
        }
        $tagCon = "";
        foreach ($tag as $key => $value) {
            if(empty($value))
                continue;
            if(empty($tagCon))
                $tagCon = 'tags:"'.$value.'"';
            else
                $tagCon = $tagCon.' OR tags:"'.$value.'"';
        }

        empty($categoryCon)?$categoryCon = "*:*":$categoryCon= $categoryCon;
        empty($brandCon)?$brandCon = "*:*":$brandCon= $brandCon;
        empty($tagCon)?$tagCon = "*:*":$tagCon= $tagCon;
        $queryKey = "({$categoryCon}) AND ({$brandCon}) AND ({$tagCon})";

        $local = CommonUtils::getLocal();

        if ($local==_LOCAL_ZN) {
            $local = _SOLR_GOODS_ZN;
        } else {
            $local = _SOLR_GOODS_EN;
        }

        $solrUtil = new SolrUtil(_SOLR_ADDRESS, $local);
        // $queryKey = "name:{$key} + technology:{$key} + brandname:{$key}";
        $fields = 'id originPrice price name icon';
        $result = $solrUtil->select(array('q'=>$queryKey,'pageSize'=>10,'fl'=>$fields,'page'=>$start,'sort'=>$sort." ".$type));

        $body = array();
        // $body['nums'] = $result['data']['response']['numFound'];
        $body = $result['data']['response']['docs'];

        echoToMobile($this->composeSearchResult($body));
    }

    private function composeSearchResult($result)
    {
        foreach ($result as $key => &$value) {
            if(!isset($value['price'])) $value['price']=$value['originPrice'];
            if(!isset($value['sells'])) $value['sells']=0;
            if(!isset($value['hots'])) $value['hots']=0;
            if(!isset($value['comments'])) $value['comments']= RedisCacheUtil::getCommentSum($value['id']);
        }
        return $result;
    }

    /**
     * @param $id
     */
    private function getSales($sid) {
        $query = array(
            'conditions' => array('_id'=>array('=='=>new MongoId($sid))),
        );
        $sales = Sales::model()->find($query);
        if (!empty($sales)) {
            return $sales;
        } else {
            echoToError(_ERROR_SYSTEM_FAULT);
        }
    }

    /**
     * 得到正在竞拍的商品竞拍信息
     * @param $id
     * @return \EMongoDocument
     */
    private function getGoodsAuction($id,$state=_GOODS_AUCTION_STATE_PROCESS) {
        $query = array(
            'conditions' => array('goods'=>array('=='=>$id),'state'=>array('=='=>$state)),
        );
        return GoodsAuctioninfo::model()->find($query);
    }

    /**
     * 浏览
     * @param $id 商品id
     * @param $deviceid 设备IDS
     */
    private function browserRecord($id,$deviceid="") {
        $useraction = new UserActionlog();
        $useraction->userid = CommonUtils::getUserId();

        $useraction->deviceid = $deviceid;

        $useraction->event = _USER_ACTION_BROWSER;
        $useraction->entityObject = $id;
        $useraction->deviceid = $deviceid;
        $useraction->entityType = _CHANNEL_GOODS;
        $useraction->createTime = time();
        $useraction->save();
        $this->addToTotal($id,_USER_ACTION_BROWSER);
    }

    private function getUser($userid) {
        $mongoid = new MongoId($userid);
        $query = array(
            'conditions' => array('_id'=>array('=='=>$mongoid)),
        );
        return UserInfo::model()->find($query);
    }

    /**
     * @param $id
     * @param $event1浏览 2购买 3评价 4 关注 5 赞 6分享
     */
    private function addToTotal($id,$event) {
        $query = array(
            'conditions' => array('goods'=>array('=='=>$id)),
        );
        $result = GoodsTotalInfo::model()->find($query);
        if (!empty($result)) {
            $info = $result;
            if ($event==_USER_ACTION_BROWSER) {
                $info->browserNum = $info->browserNum+1;
            } else if ($event==_USER_ACTION_SALES){
                $info->salesNum =$info->salesNum+1;
            } else if ($event==_USER_ACTION_COMMENT) {
                $info->commentNum = $info->commentNum+1;
            } else if ($event==_USER_ACTION_FAVORITES) {
                $info->favoritesNum =$info->favoritesNum+1;
            } else if ($event==_USER_ACTION_PRISE) {
                $info->priseNum =$info->priseNum+1;
            } else if ($event==_USER_ACTION_SHARE) {
                $info->shareNum=$info->shareNum+1;
            }
            $info->save();
        } else {
            $info = new GoodsTotalInfo();
            $info->goods = $id;
            if ($event==_USER_ACTION_BROWSER) {
                $info->browserNum = 1;
            } else if ($event==_USER_ACTION_SALES){
                $info->salesNum = 1;
            } else if ($event==_USER_ACTION_COMMENT) {
                $info->commentNum = 1;
            } else if ($event==_USER_ACTION_FAVORITES) {
                $info->favoritesNum = 1;
            } else if ($event==_USER_ACTION_PRISE) {
                $info->priseNum = 1;
            } else if ($event==_USER_ACTION_SHARE) {
                $info->shareNum = 1;
            }
            $info->save();
        }
        RedisCacheUtil::writeHotsCache($id,$event);
        $this->updateHots($id,RedisCacheUtil::getGoodsHot($id));
    }


    /**
     * 是否已经收藏
     */
    private  function hasFavorites($id) {
        if(isset($_SESSION[_SESSIONID])) {
            $userid = CommonUtils::getUserId();
            $query = array(
                'conditions' => array('username'=>array('=='=>$userid),'event'=>array('=='=>_USER_ACTION_FAVORITES),'entityObject'=>array('=='=>$id)),
            );
            $actions = UserActionlog::model()->find($query);
            if (!empty($actions)) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }



    public function actionConvert() {
        $d = new Order();
        if (is_object($d)) {
            // Gets the properties of the given object
            // with get_object_vars function
            $d = get_object_vars($d);
        }

        if (is_array($d)) {
            $d['aaa'] = "aaa";
            echoToMobile($d);
        }
    }


    private function updateHots($id,$hots)
    {
        $this->updateIndex($id,'hots',$hots);
    }

    private function updateSells($id,$sells)
    {
        $this->updateIndex($id,'sells',$sells);
    }

    private function updateIndex($id,$key,$value)
    {
        $solrUtil = new SolrUtil(_SOLR_ADDRESS, _SOLR_GOODS_ZN);
        $data = $solrUtil->update(array('id' => $id,$key=>array('set'=>$value)));

        $solrUtil = new SolrUtil(_SOLR_ADDRESS, _SOLR_GOODS_EN);
        $data = $solrUtil->update(array('id' => $id,$key=>array('set'=>$value)));
    }


}